// 常见工具类
import config from "./config.js";
import request from "./request.js";
import ffmpeg from "./ffmpeg.js";
export default {
	
	// 获取token
	token() {
		if (this.isLogin()) {
			return this.getUserInfo().token;
		} else {
			return "";
		}
	},
	
	// toast提示
	toast(msg, image, position, duration) {
		this.feedbackGeneratorState();
		if (config.osName === 1) {
			// #ifdef APP
				plus.nativeUI.toast(msg, {
					verticalAlign: "center",
					icon: image ? image : "none",
					background: "rgba(0,0,0,0.6)",
				});
			return;
			// #endif
		}
		
		uni.showToast({
			icon: "none",
			image: image ? image : undefined,
			title: msg,
			position: position || "center",
			duration: duration || 1500,
		});
	},
	
	// alert提示
	alert(option) {
		uni.showModal({
			title: option.title || "提示",
			content: option.content || "弹窗内容",
			showCancel: false,
			confirmText: option.confirmText || "确认",
			confirmColor: option.confirmColor || "#475BC3",
			success: function (res) {
				option.success && option.success();
			},
		});
	},
	
	// confirm提示
	confirm(option) {
		uni.showModal({
			title: option.title || "提示",
			content: option.editable != true ? option.content || "弹窗内容" : option.content || undefined,
			cancelText: option.cancelText || "取消",
			cancelColor: option.cancelColor || "#000000",
			confirmText: option.confirmText || "确认",
			confirmColor: option.confirmColor || "#475BC3",
			editable: option.editable || false,
			placeholderText: option.placeholderText || "",
			success: function (res) {
				if (res.confirm) {
					option.success && option.success(res);
				}
				if (res.cancel) {
					option.error && option.error(res);
				}
			},
		});
	},
	
	// 获取App版本
	getAppVersion(){
		// #ifndef APP
		return "1.0.0";
		// #endif
		
		// #ifdef APP
		return plus.runtime.version;
		// #endif
		
	},
	
	// 判断是否安装了某个App
	isApplication(e) {
		// #ifdef APP
		let isInstall = plus.runtime.isApplicationExist(e);
		if (isInstall) {
			return true;
		} else {
			return false;
		}
		// #endif
		// #ifndef APP-PLUS
		return false;
		// #endif
	},
	
	// 获取当前使用设备
	getUseType() {
		// #ifdef APP
		return "app";
		// #endif
	
		// #ifdef H5
		let uawx = navigator.userAgent.toLowerCase();
		let isWeixin = uawx.indexOf("micromessenger") != -1;
		if (isWeixin) {
			return "wechat";
		}
	
		return "h5";
		// #endif
	
		// #ifdef MP-WEIXIN
		return "wxmp";
		// #endif
	
		return "unknown";
	},
	
	// 加载loading
	showLoading(e) {
		// #ifdef APP
		plus.nativeUI.closeWaiting();
		plus.nativeUI.showWaiting(e && e.title != undefined ? e.title : "", {
			width: "95px",
			height: "95px",
			modal: e && e.mask != undefined ? e.mask : true,
			round: "15px",
			back: "close",
			background: "rgba(0,0,0,0.7)",
			loading: {
				display: "block",
			},
		});
		// #endif
	
		// #ifndef APP
		uni.hideLoading();
		uni.showLoading({ mask: true, title: e.title || "加载中" });
		// #endif
	},
	
	// 隐藏loading
	hideLoading() {
		// #ifdef APP
		plus.nativeUI.closeWaiting();
		// #endif
	
		// #ifndef APP-PLUS
		uni.hideLoading();
		// #endif
	},
	
	// 生成随机字符串
	random_char(n) {
		let random_charset = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",];
		let res = "";
		for (let i = 0; i < n; i++) {
			let id = Math.ceil(Math.random() * 35);
			res += random_charset[id];
		}
		return res;
	},
	
	// 获取当前渠道号
	getChannel() {
		// #ifdef APP
		let channel = uni.getStorageSync("channel");
		if(channel){
			return channel;
		}
		
		if (config.osName === 1) {
			return "AppStore";
		} else {
			return plus.runtime.channel || "app";
		}
		// #endif
	
		// #ifndef APP-PLUS
		return "h5";
		// #endif
	},
	
	// 触感反馈
	feedbackGeneratorState() {
		// #ifdef APP-PLUS
		if (config.osName === 1) {
			let UISelectionFeedbackGenerator = plus.ios.importClass(
				"UISelectionFeedbackGenerator"
			);
			let impact = new UISelectionFeedbackGenerator();
			impact.init();
			impact.selectionChanged();
		} else if (config.osName === 2) {
			plus.device.vibrate(12);
		}
		// #endif
	},
	
	// 将数组的顺序打乱
	shuffle(arry) {
		let array = JSON.parse(JSON.stringify(arry));
		let m = array.length, t, i;
		while (m) {
			i = Math.floor(Math.random() * m--);
			t = array[m];
			array[m] = array[i];
			array[i] = t;
		}
		return array;
	},
	
	// 延迟事件
	timeoutTimer: null,
	
	// 延迟指定秒数
	setTimeoutSync(time){
		let _this = this;
		return new Promise((resolve, reject) => {
			_this.timeoutTimer = setTimeout(() => {
				clearTimeout(_this.timeoutTimer);
				resolve();
			}, time);
		});
	},
	
	// 转换数字
	castNum(num) {
	    if (num < 10000) {
	        return num;
	    } else if (num >= 10000 && num < 100000000) {
	        let newNum = (num / 10000).toFixed(1) + "万";
	        return newNum;
	    } else if (num >= 100000000 && num < 10000000000000000) {
	        let newNum = (num / 100000000).toFixed(2) + "亿";
	        return newNum;
	    } else if (num >= 10000000000000000 && num < 1000000000000000000000000) {
	        let newNum = (num / 10000000000000000).toFixed(2) + "亿亿";
	        return newNum;
	    } else {
	        let newNum = "亿亿以上+";
	        return newNum;
	    }
	},
	
	// 返回上一页方法  force代表是否强制返回首页
	goBack(force) {
		const len = getCurrentPages().length;
		if (len === 1) {
			if (this.getRoute() !== "/pages/index/index") {
				// #ifdef H5
				uni.reLaunch({ url: "/pages/index/index" });
				// #endif
	
				// #ifndef H5
				uni.navigateBack({ delta: 1 });
				// #endif
			}
		} else {
			if (force) {
				uni.navigateBack({ delta: len - 1 });
			} else {
				uni.navigateBack({ delta: 1 });
			}
		}
	},
	
	// 分享
	openShare(opt){
		opt.done = opt.done || function (res) { };
		
		let option = {
			provider: opt.type || "weixin",
			scene: opt.scene || "WXSceneSession",
			type: opt.type_id || 0,
			href: opt.url || "",
			title: opt.title || "",
			summary: opt.content || "",
			imageUrl: opt.image || "",
			//imageUrl:"https://static.zhubazhuan.com/avatar/001/1/1818862.png",
			success: function (res) {
				opt.done(true);
			},
			fail: function (err) {
				opt.done(false);
			},
		};
		
		if (opt.type == "system") {
			uni.shareWithSystem(option);
		} else {
			uni.share(option);
		}
	},
	
	// 获取当前页面路由地址
	getRoute(force) {
		let pageList = getCurrentPages();
		let page = "";
		if (pageList.length > 0) {
			page = "/" + pageList[pageList.length - 1].route;
		}
		if (force) {
			page = page.replace(/\//g, "_");
			return page;
		} else {
			return page;
		}
	},
	
	// 通用跳转页面
	openUrl(option) {
		let _this = this;
		// #ifdef APP
		if (this.getRoute() == option.url) {
			console.log("当前处于 " + option.url + " 此页面，因此不需跳转");
			return;
		}
		// #endif
		_this.hideKeyboard();
	
		// 不处于白名单，并且未登录状态
		/*if (config.noMustLogin.indexOf(option.url) == -1 && !_this.isLogin()) {
			_this.toLogin();
			return;
		}*/
	
		let data = {
			url: option.url,
			data: option.data || {},
			animationType: option.animationType || "pop-in",
			animationDuration: 250,
			success: option.success || function(){},
			fail: option.fail || function(){}
		};
	
		let params = Object.keys(data.data).map(function (key) { return (encodeURIComponent(key) + "=" + encodeURIComponent(data.data[key])); }).join("&");
		data.url += "?" + params;
	
		if (option.openType == "navigateTo" || option.openType == undefined) {
			uni.navigateTo(data);
		} else if (option.openType == "redirectTo") {
			uni.redirectTo(data);
		} else if (option.openType == "reLaunch") {
			uni.reLaunch(data);
		} else if (option.openType == "switchTab") {
			_this.feedbackGeneratorState();
			uni.switchTab(data);
		}
	},
	
	// 会员到期时间转换
	vipExpire(time){
		if(this.getDateTimeStamp(time) - new Date().getTime() >= 60 * 1000 * 60 * 24 * 365 * 25){ // 超过25年的算永久
			return "永久会员";
		}else{
			return this.toTime(time, 'YYYY/MM/DD');
		}
	},
	
	// 数据库时间转换为普通的时间戳
	mysqlTimeto(time) {
		let myDate = new Date(time + "+0800");
		if (myDate == "Invalid Date") {
			time = time.replace(/T/g, " "); //去掉T
			time = time.replace(/-/g, "/");
			time = time.replace(/\.\d+/, " "); //去掉毫秒
			myDate = new Date(time + "+0800");
			return myDate;
		} else {
			return myDate;
		}
	},
	
	// 时间戳转换为时间
	timestampToTime(timestamp, zh) {
		let date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
		let Y = date.getFullYear() + (zh ? "年" : "-");
		let M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + (zh ? "月" : "-");
		let D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + (zh ? "日 " : " ");
		let h = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
		let m = (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":";
		let s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
		return Y + M + D + h + m + s;
	},
	
	// 数据库时间转换成时间戳或者MM/DD
	toTime(strTime, type) {
		let myDate;
		if (strTime) {
			myDate = this.mysqlTimeto(strTime);
		} else {
			myDate = new Date();
		}
	
		let year = myDate.getFullYear();
		let month = myDate.getMonth() + 1;
		if (month < 10) {
			month = "0" + month;
		}
		let day = myDate.getDate();
		if (day < 10) {
			day = "0" + day;
		}
		let hours = myDate.getHours();
		if (hours < 10) {
			hours = "0" + hours;
		}
		let minute = myDate.getMinutes();
		if (minute < 10) {
			minute = "0" + minute;
		}
		let second = myDate.getSeconds();
		if (second < 10) {
			second = "0" + second;
		}
		if (type == "MM/DD") {
			return month + "/" + day;
		} else if (type == "YYYY/MM/DD hh:mm") {
			return year + "/" + month + "/" + day + " " + hours + ":" + minute;
		} else if (type == "YYYY/MM/DD hh:mm:ss") {
			return (year +"/" +month +"/" +day +" " +hours +":" +minute +":" +second);
		} else if (type == "hh:mm:ss") {
			return hours + ":" + minute + ":" + second;
		} else if (type == "MM/DD hh:mm") {
			return month + "/" + day + " " + hours + ":" + minute;
		} else if (type == "MM/DD hh:mm:ss") {
			return month + "/" + day + " " + hours + ":" + minute + ":" + second;
		} else if (type == "YYYY/MM/DD") {
			return year + "/" + month + "/" + day;
		} else if (type == "YYYYMMDDhhmmss") {
			return (year +"" +month +"" +day +"" +hours +"" +minute +"" +second +"");
		} else if (type == "YYYYMMDD") {
			return year + "" + month + "" + day;
		} else if (type == "YYYY/MM") {
			return year + "/" + month;
		} else if (type == "YYYY-MM") {
			return year + "-" + month;
		} else {
			return myDate;
		}
	},
	
	// 将字符串时间转换为时间戳
	getDateTimeStamp(dateStr) {
		return Date.parse(("" + dateStr).replace(/-/gi, "/"));
	},
	
	// 将时间戳转换为xx之前
	getDateDiff(time, type) {
		let publishTime = Math.ceil(time / 1000),
			d_seconds,
			d_minutes,
			d_hours,
			d_days,
			timeNow = parseInt(new Date().getTime() / 1000),
			d,
			date = new Date(publishTime * 1000),
			Y = date.getFullYear(),
			M = date.getMonth() + 1,
			D = date.getDate(),
			H = date.getHours(),
			m = date.getMinutes(),
			s = date.getSeconds();
		//小于10的在前面补0
		if (M < 10) {
			M = "0" + M;
		}
		if (D < 10) {
			D = "0" + D;
		}
		if (H < 10) {
			H = "0" + H;
		}
		if (m < 10) {
			m = "0" + m;
		}
		if (s < 10) {
			s = "0" + s;
		}
	
		d = timeNow - publishTime;
		d_days = parseInt(d / 86400);
		d_hours = parseInt(d / 3600);
		d_minutes = parseInt(d / 60);
		d_seconds = parseInt(d);
	
		if (d_days > 0 && d_days < 2) {
			return d_days + "天前";
		} else if (d_days <= 0 && d_hours > 0) {
			return d_hours + "小时前";
		} else if (d_hours <= 0 && d_minutes > 0) {
			return d_minutes + "分钟前";
		} else if (d_seconds < 60) {
			if (d_seconds <= 0) {
				return "刚刚";
			} else {
				return d_seconds + "秒前";
			}
		} else {
			if (type == "article") {
				if (d_days >= 2 && d_days < 30) {
					return M + "-" + D;
				} else if (d_days >= 30) {
					return Y + "-" + M + "-" + D;
				}
			} else {
				if (d_days >= 2 && d_days < 30) {
					return M + "-" + D + " " + H + ":" + m;
				} else if (d_days >= 30) {
					return Y + "-" + M + "-" + D + " " + H + ":" + m;
				}
			}
		}
	},
	
	// 登录或退出后，需刷新的地方
	reshMyInfo() {
		uni.$emit("updateCreate");
		uni.$emit("updateIndex");
		uni.$emit("updateMyVip");
	},
	
	// 登录成功
	loginSuccess(data) {
		this.setUserInfo(data);
		this.reshMyInfo();
	},
	
	// 退出登录
	loginExit() {
		this.removeUserInfo();
		this.reshMyInfo();
		setTimeout(() => {
			if (getCurrentPages().length > 1) {
				uni.navigateBack({
					delta: getCurrentPages().length,
				});
			}
		}, 300);
	},
	
	// 获取用户信息
	getUserInfo() {
		if (uni.getStorageSync("userInfo")) {
			return uni.getStorageSync("userInfo");
		} else {
			return false;
		}
	},
	
	// 写入用户信息
	setUserInfo(data) {
		uni.setStorageSync("userInfo", data);
	},
	
	// 删除用户信息
	removeUserInfo() {
		uni.removeStorageSync("userInfo");
	},
	
	// 是否处于登录
	isLogin() {
		if (uni.getStorageSync("userInfo")) {
			return true;
		} else {
			return false;
		}
	},
	
	// 跳转到登录页
	toLogin(isBack = false) {
		this.openUrl({ url: "/pages/user/login", animationType: "slide-in-bottom" });
		return;
		
		// #ifdef APP
		this.openUrl({ url: "/pages/user/login", animationType: "slide-in-bottom" });
		// #endif
		
		// #ifndef APP
		this.openUrl({ url: "/pages/user/mobileLogin", animationType: "slide-in-bottom" });
		// #endif
	},
	
	// 获取虚拟陪伴信息
	getAccompanyInfo() {
		if (uni.getStorageSync("accompanyInfo")) {
			return uni.getStorageSync("accompanyInfo");
		} else {
			return false;
		}
	},
	
	// 写入虚拟陪伴信息
	setAccompanyInfo(data) {
		uni.setStorageSync("accompanyInfo", data);
	},
	
	// 获取口语信息
	getSpokenInfo() {
		if (uni.getStorageSync("spokenInfo")) {
			return uni.getStorageSync("spokenInfo");
		} else {
			return false;
		}
	},
	
	// 写入口语信息
	setSpokenInfo(data) {
		uni.setStorageSync("spokenInfo", data);
	},
	
	// 将json对象的key 按升序排序
	sortObjectFields(obj) {
		// 将obj的key转换为小写
		let lowerObj = {};
		for(let i in obj){
			lowerObj[i.toLowerCase()] = obj[i];
		}
		
		// 将obj按升序排序
		let newkey = Object.keys(lowerObj).sort();
		
		// 返回新的对象
		let newObj = {};
		newkey.map((item) => newObj[item] = lowerObj[item]);
		return newObj;
	},
	
	// 打开一键登录界面
	openUniverify(option) {
		let _this = this;
		uni.login({
			provider: "univerify",
			univerifyStyle: {
				closeIcon: {
					path: "static/img/login_close.png", // 自定义关闭按钮，仅支持本地图片。 HBuilderX3.3.7+版本支持
				},
				icon: {
					path: "static/img/logo.png", // 自定义显示在授权框中的logo，仅支持本地图片 默认显示App logo
				},
				backgroundColor: "#232526", // 授权页面背景颜色，默认值：#ffffff
				fullScreen: false,
				phoneNum: {
					color: "#FFFFFF", // 手机号文字颜色 默认值：#202020
				},
				slogan: {
					color: "rgba(255,255,255,0.6)", //  slogan 字体颜色 默认值：#BBBBBB
				},
				authButton: {
					title: option.buttonText || "本机号码一键登录",
					textColor: "#000000",  // 授权按钮文字颜色 默认值：#ffffff
					disabledColor: "rgba(255,255,255,0.6)",
					normalColor: "rgba(255,255,255,0.95)", // 授权按钮正常状态背景颜色 默认值：#3479f5
					highlightColor: "rgba(255,255,255,0.8)", // 授权按钮按下状态背景颜色 默认值：#2861c5（仅ios支持）
				},
				otherLoginButton: {
					textColor: "rgba(255,255,255,0.6)", // 其他登录按钮文字颜色 默认值：#656565
					title: option.otherButtonText || "短信验证码登录", // 其他登录方式按钮文字 默认值：“其他登录方式”
				},
				privacyTerms: {
					checkBoxSize: 26,
					defaultCheckBoxState: config.osName === 1 ? true : false, // 条款勾选框初始状态 默认值： true
					uncheckedImage: config.osName === 1 ? undefined : "static/img/login_green.png", // 可选 条款勾选框未选中状态图片（仅支持本地图片 建议尺寸 24x24px）(3.2.0+ 版本支持)checkedImage: system.platform == "ios" ? undefined :"/static/img/login_green_active.png", // 可选 条款勾选框选中状态图片（仅支持本地图片 建议尺寸24x24px）(3.2.0+ 版本支持)
					checkedImage: config.osName === 1 ? undefined : "static/img/login_green_active.png", // 可选 条款勾选框选中状态图片（仅支持本地图片 建议尺寸24x24px）(3.2.0+ 版本支持)
				},
			},
			success(res) {
				// 登录成功
				_this.hideLoading();
				option.success && option.success(res);
			},
			fail(res) {
				// 登录失败
				if (res.errCode == 30003) {
					//用户关闭验证界面
				} else if (res.errCode == 30008) {
					//用户点击了自定义按钮
					option.error && option.error(res);
				} else {
					if (res.errCode != 30002 && res.errCode != 20202 && res.errCode != 30005) {
						_this.toast(res.errMsg);
					}
					option.error && option.error(res);
				}
	
				_this.hideLoading();
				uni.closeAuthView();
			},
			complete() {
				// 预取号
				uni.preLogin({ provider: "univerify" });
				uni.closeAuthView();
			},
		});
	},
	
	// 获取某个uniapp打包的第三方服务
	getServices(type = 'share', serviceName = 'weixin') {
		return new Promise((resolve, reject) => {
			plus[type].getServices((services) => {
				let item = null;
				for (const service of services) {
					if (service.id === serviceName) {
						item = service;
					}
				}
	
				if (item) {
					resolve(item);
				} else {
					reject(`没有找到${serviceName}服务`);
				}
			}, (err) => {
				reject(err);
			});
		})
	},
	
	// 隐藏键盘
	hideKeyboard() {
		uni.hideKeyboard();
	},
	
	// 秒数转换为分：秒 格式
	secondToDuration(time, zh, hours) {
		let second = parseInt(time);
		if (isNaN(second)) {
			return "-";
		}
	
		if (hours || time >= 3600) {
			let returnHours = Math.floor(time / 3600);
			let suprSecond = time % 3600;
			let returnMinute = Math.floor(suprSecond / 60);
			let returnSecond = Math.floor(suprSecond % 60);
			if (returnHours < 10) {
				returnHours = "0" + returnHours;
			}
			if (returnMinute < 10) {
				returnMinute = "0" + returnMinute;
			}
			if (returnSecond < 10) {
				returnSecond = "0" + returnSecond;
			}
	
			if (zh) {
				return `${returnHours}时${returnMinute}分${returnSecond}秒`;
			} else {
				return `${returnHours}:${returnMinute}:${returnSecond}`;
			}
		} else {
			let returnMinute = Math.floor(time / 60);
			let returnSecond = Math.floor(time % 60);
			if (returnMinute == -1 || returnSecond == -1) {
				return "-";
			}
	
			if (returnMinute < 10) {
				returnMinute = "0" + returnMinute;
			}
			if (returnSecond < 10) {
				returnSecond = "0" + returnSecond;
			}
	
			if (zh) {
				return `${returnMinute}分${returnSecond}秒`;
			} else {
				return `${returnMinute}:${returnSecond}`;
			}
		}
	},
	
	// 将bytes转为尺寸
	bytesToSize(bytes) {
		let sizes = ["Bytes", "KB", "MB", "GB", "TB"];
		if (bytes == 0) {
			return "0 Byte";
		}
		let i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
		return (bytes / Math.pow(1024, i)).toFixed(2) + sizes[i];
	},
	
	// 弹出AppStore评分
	storeKit() {
		// #ifdef APP
		if (config.osName === 1) {
			let storeKit = uni.requireNativePlugin("Xty-StoreKit");
			let storeKitStroage = uni.getStorageSync("storeKitStroage");
			if (storeKitStroage) {
				if (new Date().getTime() - storeKitStroage >= 86400000 * 30) {
					//30天以内弹过就不弹出了
					storeKit.review();
					uni.setStorageSync("storeKitStroage", new Date().getTime());
				}
			} else {
				storeKit.review();
				uni.setStorageSync("storeKitStroage", new Date().getTime());
			}
		}
		// #endif
	},
	
	// 获取文件扩展名
	getSuffix(filename) {
		let pos = filename.lastIndexOf(".");
		let suffix = "";
		if (pos != -1) {
			suffix = filename.substring(pos + 1);
		}
		return suffix.toLowerCase();
	},
	
	
	// 根据oss配置和路径，获取一下完整的http路径
	getFullOssPath(path) {
		return `${config.oss}/storage/${config.productCode}${path}`;
	},
	
	// 获取当前是测试服还是正式服
	getServerProd() {
		let apiServer = uni.getStorageSync("apiServer");
		if (apiServer) {
			if (apiServer == "dev" || apiServer == "prod") {
				return apiServer;
			} else {
				return "prod";
			}
		} else {
			return process.env.NODE_ENV === "development" ? "dev" : "prod";
		}
	},
	
	// 获取胶囊位置
	menuButtonBounding() {
		// #ifdef MP
		return uni.getMenuButtonBoundingClientRect();
		// #endif
	
		// #ifndef MP
		return {bottom: 0,height: 0,left: 0,right: 0,top: 0,width: 0,};
		// #endif
	},
	
	// 获取App名称以及logo
	getAppInfoDesc() {
		return {
			indexLogo: "/static/img/index_logo.png",
			logo: "/static/img/logo.png",
			loginDesc: "/static/img/login_text.png",
			name: config.systemInfo.appName,
			content: `人工智能助理,AI艺术生成器,工作帮手,生活助手,尽在${config.systemInfo.appName}`,
		};
	},
	
	// 获取包名
	getPackageName() {
		// #ifdef APP
		if (config.osName === 1) {
			// 获取苹果应用包名（bundleId）
			return plus.ios.importClass('NSBundle').mainBundle().bundleIdentifier();
		} else {
			// 获取安卓应用包名  
			return plus.android.runtimeMainActivity().getPackageName();
		}
		// #endif
	
		return "h5";
	},
	
	// 登出某个授权登录的服务
	empowerLogout(type) {
		return new Promise((resolve, reject) => {
			plus.oauth.getServices(function (services) {
				for (let i in services) {
					if (services[i].id === type) {
						services[i].logout(function (e) {
							resolve();
						}, function (e) {
							reject();
						});
					}
				}
			}, function (e) {
				reject();
			});
		});
	},
	
	// 打开用户协议或隐私政策
	openUserPrivacy(type = 'privacy') {
		this.openUrl({ url: '/pages/index/outUrl', data: { url: `${config.host}/${type}.html?channel=${this.getChannel()}` } });
	},
	
	// rpx转为px
	rpx2px(rpx) {
		return (config.systemInfo.screenWidth / 750 * rpx);
	},
	
	// 或者某某之间的随机数
	getRandomInt(min, max) {
		return Math.floor(Math.random() * (max - min + 1)) + min;
	},
	
	// 将文本分割为多段
	chunkText(str = "", count = 200){
		let chunks = [];
		do {
			let splitIndex = -1;
			for (let i = count; i < str.length; i++) {
				if ([",", ".", ";", "，", "。", "；", "、", "\n"].includes(str[i])) {
					splitIndex = i + 1;
					break;
				}
			}
			chunks.push(str.substring(0, splitIndex === -1 ? str.length : splitIndex));
			str = str.substring(splitIndex === -1 ? str.length : splitIndex);
		
			if (str.length <= count) {
				chunks.push(str);
				break;
			}
		} while (true);
		
		let start = 0;
		chunks = chunks.filter(text => !!text).map(text => ({
			text,
			startIdx: start,
			endIdx: start += text.length,
		}));
		
		return chunks;
	},
	
	// 将一个数组分割为多个数组
	chunkArray(array, size) {
		//获取数组的长度，如果你传入的不是数组，那么获取到的就是undefined
		let length = array.length;
		//判断不是数组，或者size没有设置，size小于1，就返回空数组
		if (!length || !size || size < 1) {
			return [];
		}
		//核心部分
		let index = 0; //用来表示切割元素的范围start
		let resIndex = 0; //用来递增表示输出数组的下标
	
		//根据length和size算出输出数组的长度，并且创建它。
		let result = new Array(Math.ceil(length / size));
		//进行循环
		while (index < length) {
			//循环过程中设置result[0]和result[1]的值。该值根据array.slice切割得到。
			result[resIndex++] = array.slice(index, (index += size));
		}
	
		//输出新数组
		return result;
	},
	
	// 设置底部安全区域背景颜色
	setSafeAreaBackgroundColor(color) {
		color || (color = "#282828");
		if (config.osName === 2) {
			let context = plus.android.runtimeMainActivity();
			let win = plus.android.invoke(context, "getWindow");
			let icolor = plus.android.invoke("android.graphics.Color", "parseColor", color);
			plus.android.invoke(win, "setNavigationBarColor", icolor);
		}
	},
		
	// 获取当前渠道是否需要强制绑定手机号码
	getForceBindMobile(){
		let _this = this;
		return new Promise((resolve, reject) => {
			_this.getAppBasic().then((e) => {
				let bindPhoneChannel = e.is_bind_mobile;
				if(bindPhoneChannel && bindPhoneChannel.channel && bindPhoneChannel.channel.indexOf(_this.getChannel()) !== -1){
					const [t1, t2] = bindPhoneChannel.effectTime.split("-").map((str) => parseInt(str.replace(/\:/g, "")));
					const now = new Date();
					const hh = now.getHours().toString().padStart(2, "0");
					const mm = now.getMinutes().toString().padStart(2, "0");
					const sd = now.getSeconds().toString().padStart(2, "0");
					const t = parseInt(hh + mm + sd);
					resolve(t1 <= t && t2 >= t);
				}else{
					resolve(false);
				}
			}).catch((err) => {
				reject(false);
			})
		});
	},
	
	// 打开联系客服
	openService() {
		let _this = this;
		_this.getAppBasic(true).then((res) => {
			if (res.customer_service) {
				// #ifdef APP
				_this.getServices("share", "weixin").then((e) => {
					e.openCustomerServiceChat(res.customer_service);
				}).catch((err) => {
					_this.toast(JSON.stringify(err));
				});
				// #endif
				// #ifdef H5
				open(res.customer_service.url, "_blank");
				// #endif
			} else {
				_this.toast("当前未找到在线客服");
			}
		}).catch((err) => {
			_this.toast(err);
		})
	},
		
	// 通用的开始播放音乐
	playMusic(e) {
		uni.$audio.stop();
		uni.$audio.loop = e.loop === undefined ? false : e.loop;
		uni.$audio.startTime = Number((e.startTime === undefined ? 0 : e.startTime) + ".000" + this.getRandomInt(0,100));
		uni.$audio.playbackRate = e.playbackRate === undefined ? 1.0 : e.playbackRate;
		uni.$audio.volume = e.volume === undefined ? 1 : e.volume;
		uni.$audio.src = e.src;
		uni.$audio.play();
		// uni.$audio.seek(e.startTime === undefined ? 0 : e.startTime);
	},
	
	// 打开图片
	openImage(index, list){
		uni.previewImage({
			urls: list,
			current: index,
			indicator: "number",
		});
	},
		
	// 编码并替换
	deReplace(str) {
		return decodeURIComponent(str).replace(/123/g, "");
	},
	
	// 解码特殊词语
	decodeWords(arr) {
		return arr.map((num) => String.fromCharCode(num)).join("");
	},
	
	// 读取某个网络文件是否存在本地缓存
	getFileCache(url, call){
		let _this = this;
		return new Promise((resolve) => {
			let storageKey = "fileCache";
			let storageResult = uni.getStorageSync(storageKey) || {};
			let filename = encodeURIComponent(url.replace(/[\.\:\\\/]/g, "_"));
			if(storageResult[filename]){
				resolve(storageResult[filename]);
			}else{
				uni.downloadFile({
					url, 
					timeout: 1000 * 60 * 60,
					success: (res) => {
						if (res.statusCode == 200) {
							uni.saveFile({
								tempFilePath: res.tempFilePath,
								success(ret){
									storageResult[filename] = ret.savedFilePath;
									uni.setStorageSync(storageKey, storageResult);
									call && call(ret.savedFilePath);
								}
							});
						}
					}
				});
				resolve(url);
			}
		})
	},
	
	// 通用获取相册图片视频
	chooseImageVideo(e){
		let _this = this;
		return new Promise((resolve) => {
			if(config.osName === 1){
				_this.chooseImageVideoRequest(e).then((res) => {
					resolve(res);
				});
			}else{
				let permissionID = "android.permission.READ_EXTERNAL_STORAGE";
				if(uni.getStorageSync(permissionID)){
					_this.chooseImageVideoRequest(e).then((res) => {
						resolve(res);
					});
				}else{
					e.alert.open({
						title: "提示",
						content: e.type === "image" ? "我们需要访问你的本地文件（含相册文件），用于上传头像或智能体图标。" : "我们需要访问你的本地文件（含相册文件），用于上传视频转写文本。",
						success(res) {
							if (res.confirm) {
								uni.setStorageSync(permissionID, true);
								_this.chooseImageVideoRequest(e).then((res) => {
									resolve(res);
								});
							}
						} 
					});
				}
			}
		});
	},
	
	// 实际获取图片视频
	chooseImageVideoRequest(e){
		let _this = this;
		return new Promise((resolve) => {
			if(e.type === "image"){
				uni.chooseImage({
					count: e.count || 1,
					sizeType: e.sizeType || ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: e.sourceType || ['album'], // 从相册选择
					compressed: e.compressed || true,
					crop: e.crop || {width: 200,height: 200,resize: true},
					success({tempFilePaths}) {
						resolve(tempFilePaths);
					},
					fail(err){
						if(err.errMsg == "chooseImage:fail No Permission"){
							uni.openAppAuthorizeSetting();
						}
					}
				});
			}else{
				uni.chooseVideo({
					sourceType: e.sourceType || ["album"],
					compressed: e.compressed || true,
					success(res) {
						resolve({
							filePath: res.tempFilePath,
							size: res.size,
							duration: res.duration,
							width: res.width,
							height: res.height,
						});
					},
					fail(err) {
						if(err.errMsg == "chooseImage:fail No Permission"){
							uni.openAppAuthorizeSetting();
						}
					},
				});
			}
		});
	},
	
	// 通用写入相册图片视频
	saveImageVideoToPhotosAlbum(e){
		let _this = this;
		return new Promise((resolve) => {
			if(config.osName === 1){
				_this.saveImageVideoToPhotosAlbumRequest(e).then((res) => {
					resolve(res);
				});
			}else{
				let permissionID = "android.permission.WRITE_EXTERNAL_STORAGE";
				if(uni.getStorageSync(permissionID)){
					_this.saveImageVideoToPhotosAlbumRequest(e).then((res) => {
						resolve(res);
					});
				}else{
					e.alert.open({
						title: "提示",
						content: e.type === "image" ? "我们需要写入你的本地文件（含相册文件），用于保存绘画。" : "我们需要写入你的本地文件（含相册文件），用于保存成片作品。",
						success(res) {
							if (res.confirm) {
								uni.setStorageSync(permissionID, true);
								_this.saveImageVideoToPhotosAlbumRequest(e).then((res) => {
									resolve(res);
								});
							}else{
								e.call && e.call({ status: false, msg: "没有赋予相册权限" });
							}
						} 
					});
				}
			}
		});
	},
	
	// 实际写入图片视频
	saveImageVideoToPhotosAlbumRequest(e){
		let _this = this;
		return new Promise((resolve) => {
			if(e.type === "image"){
				uni.saveImageToPhotosAlbum({
					filePath: e.filePath,
					success(){
						resolve({ status: true });
					},
					fail(){
						if(err.errMsg == "chooseImage:fail No Permission"){
							uni.openAppAuthorizeSetting();
						}else{
							resolve({ status: false });
						}
					}
				});
			}else{
				uni.saveVideoToPhotosAlbum({
					filePath: e.filePath,
					success(){
						resolve({ status: true });
					},
					fail(){
						if(err.errMsg == "chooseImage:fail No Permission"){
							uni.openAppAuthorizeSetting();
						}else{
							resolve({ status: false });
						}
					}
				});
			}
		});
	},
	
	// 判断是否有麦克风权限
	microphoneAuthorize(e){
		let _this = this;
		let authorize = uni.getAppAuthorizeSetting();
		return new Promise((resolve) => {
			if (authorize.microphoneAuthorized == "authorized") {
				resolve();
			} else if (authorize.microphoneAuthorized == "denied") {
				e.alert.open({
					title: "提示",
					content: "我们需要录音权限，以便实现实时语音转文字功能",
					confirmText: "去开启",
					success(res) {
						if (res.confirm) {
							if(config.osName === 1){
								uni.openAppAuthorizeSetting();
							}else{
								let permissionID = "android.permission.RECORD_AUDIO";
								if(uni.getStorageSync(permissionID)){
									uni.openAppAuthorizeSetting();
								}else{
									uni.setStorageSync(permissionID, true);
									uni.$recorder.start();
									uni.$recorder.stop();
								}
							}
						}
					}
				});
			} else if (authorize.microphoneAuthorized == "not determined") {
				// 从未调用权限的，可以先随便调用下麦克风请求下权限。
				uni.$recorder.start();
				uni.$recorder.stop();
			} else if (authorize.microphoneAuthorized == "config error") {
				e.alert.open({
					title: "提示",
					content: "麦克风错误_请联系客服",
					showCancel: false,
				});
			}
		});
	},
	
};